package com.atguigu.flink.charkoer13;

import com.atguigu.flink.been.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.client.program.StreamContextEnvironment;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;


public class FlinkSqlTableApi {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamContextEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

//        1.先获取一个流
        DataStreamSource<WaterSensor> dataStreamSource = env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_1", 2000L, 20),
                new WaterSensor("sensor_2", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_1", 5000L, 50),
                new WaterSensor("sensor_2", 6000L, 60)
        );

//        2.把流转成动态表
        // 2.1 先有个表的执行环境
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        // 2.2 通过表的执行环境转成流
        Table table = tEnv.fromDataStream(dataStreamSource);
//        3.在动态表上执行连续查询，得到一个新的动态表
        Table table1 = table
                .groupBy($("id"))
                .aggregate($("vc").sum().as("vc_sum"))
                .select($("id").as("id1"), $("vc_sum"));
//        4.把结果转换成流
        DataStream<Tuple2<Boolean, Row>> rowDataStream = tEnv.toRetractStream(table1, Row.class);

        rowDataStream.print();

        env.execute();

    }
}
